/***************************************************************************
 * File name: q1.c
 * Author:  Tomer Filiba
 *          037013075
 *          sebulba@t2
 *
 * Exercise #: 3
 * Question #: 1
 * Submission Date: 01/7/07
 **************************************************************************/

/*-------------------------------------------------------------------------
  Include files:
--------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>

/*=========================================================================
  Constants and definitions:
==========================================================================*/
#define GREAT_SUCCESS		(0)
#define BIG_BAGA_BOOM		(1)

/* enum of formatter states */
enum formatter_states_t
{
	FS_WHITESPACE,
	FS_TEXT,
	FS_PERIOD,
	FS_EMAIL,
};

/*-------------------------------------------------------------------------
  Reformat text read from STDIN, count number of emails
 -------------------------------------------------------------------------*/
int main(int argc, const char ** argv) 
{
	int c, emails_count = 0;
	enum formatter_states_t state = FS_TEXT;
	
	/* the text is read from stdin, we assume it's done via redirection 
	 * otherwise the text on the screen would get messy */
	
	printf("Reformatted text:\n-----------------\n");
	
	while ((c = getchar()) != EOF)
	{
		switch (c)
		{
		case ' ':
		case '\t':
		case '\n':
		case '\r':
			/* ignore consecutive spaces, and don't print a space 
			 * rigt after a newline */
			if (state != FS_PERIOD && state != FS_WHITESPACE) {
				putchar(' ');
			}
			state = FS_WHITESPACE;
			break;
		case '.':
		case '?':
		case '!':
			/* don't treat periods inside emails and don't print multiple
			 * newlines for consecutive periods (...). also, if the last char
			 * was a whitespace, delete it */
			if (state == FS_WHITESPACE) {
				putchar('\b');
			}
			putchar(c);
			if (state != FS_EMAIL && state != FS_PERIOD) {
				state = FS_PERIOD;
				putchar('\n');
			}
			break;
		case '@':
			putchar(c);
			state = FS_EMAIL;
			emails_count += 1;
			break;
		default:
			/* normal text, unless inside an email address */
			if (state != FS_EMAIL) {
				state = FS_TEXT;
			}
			putchar(c);
			break;
		}
	}
	
	/* print number of emails */
	printf("\n\nNumber of email addresses found: %d\n", emails_count);
	return GREAT_SUCCESS;
}

/**************************************************************************
                               End of file
***************************************************************************/